import 'dart:convert';
import 'package:delivery_application/model/order_model.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:delivery_application/common_widget/round_button.dart';
import 'package:delivery_application/common_widget/round_textfield.dart';
import 'package:delivery_application/view/home/myorder.dart';

class SearchView extends StatefulWidget {
  const SearchView({super.key});

  @override
  State<SearchView> createState() => _SearchViewState();
}

class _SearchViewState extends State<SearchView> {
  List<Order> searchResults = [];
  TextEditingController searchController = TextEditingController();

  Future<void> _searchOrders() async {
    final prefs = await SharedPreferences.getInstance();
    final orderStrings = prefs.getStringList('orders') ?? [];
    final allOrders = orderStrings
        .map((str) => Order.fromJson(jsonDecode(str)))
        .toList();

    setState(() {
      if (searchController.text.isEmpty) {
        searchResults = [];
      } else {
        searchResults = allOrders
            .where((order) =>
                order.orderNumber.toLowerCase().contains(searchController.text.toLowerCase()))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff00AEEE),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              const SizedBox(height: 40),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const MyOrder(),
                        ),
                      );
                    },
                    child: const Text(
                      '查看历史订单',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
              RoundTextfield(
                hintText: "请输入订单号",
                controller: searchController,
                keyboardType: TextInputType.text,
              ),
              const SizedBox(height: 20),
              RoundButton(
                title: "查询",
                onPressed: _searchOrders,
              ),
              const SizedBox(height: 20),
              Expanded(
                child: searchResults.isEmpty
                    ? const Center(
                        child: Text(
                          '无查询结果',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                      )
                    : ListView.builder(
                        itemCount: searchResults.length,
                        itemBuilder: (context, index) {
                          final order = searchResults[index];
                          return Card(
                            margin: const EdgeInsets.symmetric(vertical: 8.0),
                            child: ListTile(
                              title: Text('订单号: ${order.orderNumber}'),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('地址: ${order.address}'),
                                  Text('创建时间: ${order.createTime.toString().split('.')[0]}'),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
